import Express from "express"
import {
    registerServ,
    updatePwdServ,
    updateUserServ,
} from "../Service/userServ.js"
import {
    loginServ
} from "../Service/userServ.js"
import {
    findUserDao
} from "../Dao/loginDao.js"
import {
    checkAuth
} from "../Service/middleware/checkAuth.js"
import {
    checkAuthServ
} from "../Service/userServ.js"
export const UserRouter = Express.Router()

UserRouter.post("/login", async (req, res) => {
    const body = req.body;
    if (!body.code) {
        res.json({
            code: 1,
            msg: "请输入验证码"
        })

        return
    }
    if (body ?.code.toUpperCase() === req.session ?.code.toUpperCase()) {
        //验证码正确
        //查数据库
        const json = await loginServ(body)
        res.json(json)
    } else {
        res.json({
            code: 1,
            msg: "验证码错误"
        })
    }
})


UserRouter.post("/register", async (req, res) => {
    const {
        username,
        nickname,
        code
    } = req.body;
    if (code ?.toUpperCase() === req.session ?.code ?.toUpperCase()) {
        await registerServ({
            username,
            nickname
        })
        res.json({
            code: 0,
            msg: "注册成功"
        })
    } else {
        res.json({
            code: 1,
            msg: "验证码错误"
        })
    }
})



UserRouter.get("/whoami", checkAuth, async (req, res) => {
    const user = await findUserDao(req.username)
    res.json({
        code: 0,
        msg: "ok",
        data: user
    })
})


UserRouter.post('/checkpwd', checkAuth, async (req, res) => {
    const {
        username,
        password
    } = req.body;
    const result = await checkAuthServ(username, password);
    res.json(result)
})

UserRouter.post("/updatepwd", checkAuth, async (req, res) => {
    const {username,password} = req.body;
    await updatePwdServ(username,password)
    res.json({
        code:0,
        msg:"修改成功"
    })
})


UserRouter.put("/:id",checkAuth,async(req,res)=>{
    const id =req.params.id;
    const body =req.body;
    const result = await updateUserServ(id,body)
    res.json(result)
})


// import Express from 'express'
// // 1. 创建路由对象 Express.Router

// export const UserRouter = Express.Router()

// UserRouter.post('/login', async (req, res) => {
//     res.json({
//         code: 0,
//         msg: "登录成功"
//     })
// })

// UserRouter.post('/register', async (req, res) => {
//     const {username,nickname,code} = req.body;
//     if(code?.toUpperCase() === req.session?.code?.toUpperCase()){
//         res.json({
//         code: 0,
//         msg: "注册成功"
//                 })
//     }else{
//          res.json({
//         code: 1,
//         msg: "验证码未通过"
//     })
//     }
// })